package com.example.rabbitdemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@Slf4j
@RequestMapping("/rocket")
public class RocketController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/topic1")
    public String send(String message){
        rocketMQTemplate.convertAndSend("rocketTopic1",message);
        log.info("已发送异步消息");
        return "ok";
    }

    @GetMapping("/testSyncSend")
    public String testSyncSend(){
        SendResult sendResult =rocketMQTemplate.syncSend("rocketTopic1", "这是一条同步消息");
        System.out.println(sendResult);
        return "ok";
    }
    @GetMapping("/testAsyncSend")
    public String testAsyncSend(){
        rocketMQTemplate.asyncSend("rocketTopic1", "这是一条异步信息", new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult);
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable);
            }
        });

        System.out.println("==============================");

        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return "ok";
    }

    /**
     * 延迟消息
     * @param message
     * @return
     */
    @GetMapping("/testTimeOut")
    public String  testPayload(String message){
        rocketMQTemplate.syncSend("rocketTopic1", MessageBuilder.withPayload(message).build(),3000,2);
        return "ok";
    }

    @GetMapping("/send/transaction")
    public String sendTransactionMessage(String message){
        TransactionSendResult result=rocketMQTemplate.sendMessageInTransaction("rocketTopic1",
                MessageBuilder.withPayload(message).build(),null);
        String status=result.getSendStatus().name();
        String localState=result.getLocalTransactionState().name();
        log.info("发送状态:"+status+";本地事务执行状态"+localState);
        return "ok";
    }





}
